package com.mbbb.yygh.msm.controller;

import com.mbbb.yygh.common.result.R;
import com.mbbb.yygh.msm.service.MsmService;
import com.mbbb.yygh.msm.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/msm")
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping(value = "/send/{phone}")
    public R code(@PathVariable String phone) {
        //设置在有效时间内不能再次发送
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)) return R.ok();

        //1 生成随机验证码
        code = RandomUtil.getFourBitRandom();

        //2 调用鼎信方法根据手机发送验证码
        boolean isSuccess = msmService.sendCode(phone,code);

        //3 发送成功，验证码放到redis，设置过期时间
        if(isSuccess) {//成功
            //验证码放到redis，设置过期时间
            //key:手机号 value：验证码
            redisTemplate.opsForValue().set(phone,code,60, TimeUnit.SECONDS);
        }
        return R.ok();
    }
}
